const models = require('../db/mysqldb/index')
const { Op } = require("sequelize");

class ChatNewFriendsModel {
  /**
   * @description 添加我的新好友通知
   * @param {string} user_id
   * @returns
   */
  static async insert (from, to, content) {
    return await models.chat_new_friends.create({
      from,
      to,
      content,
    })
  }

  /**
   * @description 获取新朋友通知
   * @param {string} user_id
   * @returns
   */
  static async find (to) {
    let sql = `SELECT
    cnf.from,
    cnf.content,
    cnf.status,
    cnf.create_timestamp,
    cnf.update_timestamp,
    su.realname,
    su.sex,
    su.phone,
    su.avatar 
  FROM
    chat_new_friends cnf
    LEFT JOIN sys_user su ON cnf.from = su.user_id WHERE cnf.delete_timestamp is null and su.delete_timestamp is NULL and cnf.to = ${to}`
    return await models.sequelize.query(sql, {
      replacements: ['active'],
      type: models.sequelize.QueryTypes.SELECT,
    })
  }

  /**
  * @description 
  * @param {string} user_id
  * @returns
  */
  static async findByUserId (from, to) {
    return await models.chat_new_friends.findAll({
      where: {
        delete_timestamp: {
          [Op.is]: null,
        },
        to,
        from,
        status: 0
      }
    })
  }

  /**
   * @description 更新
   * @param {string} status
   * @returns
   */
  static async update (from, to, content) {
    return await models.chat_new_friends.update({
      update_timestamp: Date.now(),
      content
    }, {
      where: {
        from, to, status: 0
      }
    })
  }

  /**
   * @description 状态更新
   * @param {string} status
   * @returns
   */
  static async updateStatus (from, to, status) {
    return await models.chat_new_friends.update({
      status,
      update_timestamp: Date.now()
    }, {
      where: {
        from, to
      }
    })
  }

  /**
   * 已读
   * @param {number} to 
   * @returns 
   */
  static async updateRead (to) {
    return await models.chat_new_friends.update({
      update_timestamp: Date.now(),
      read: 1
    }, {
      where: {
        to
      }
    })
  }
}
module.exports = {
  ChatNewFriendsModel,
}
